import { APICartList, APICartUpdate, APICartDelete } from './fetch.js';
import { getCookie } from './tools.js';


$('#head').load('../../layout/head.html');
$('#footer').load('../../layout/footer.html');

layui.use(['layer'], function () {
  var layer = layui.layer;

  var username = getCookie('login_user');

  APICartList({
    username
  }).then(({ data }) => {
    var html = '';
    $.each(data, (index, { gname, img, price, count, id }) => {
      html +=`
        <tr data-id="${id}">
          <td class="td1">
            <input type="checkbox" class="check-one">
          </td>
          <td class="td2">
            <img src="${img}" alt="">
          </td>
          <td class="td3">
            <span>${gname}</span>
            <p>${price}</p>
          </td>
          <td class="td4">
            <div class="td4_1">
              <span class="sp1">${count > 1 ? '-' : ''}</span>
              <input type="text" class="sp2" value="${count}">
              <span class="sp3">+</span>
            </div>
          </td>
          <td class="td5"><span>￥</span>
            <p>${(price * count).toFixed(2)}</p>
          </td>
          <td class="td6">
            <i class="layui-icon layui-icon-delete"></i>
          </td>
        </tr>`
    })

    $('.cart-list').html(html);

  })

  var timer = null;

  $(document).on('click','.sp3',function(){

    updateCount(this,1);

    $(this).parents('tr').find('.sp1').text('-');
  })

  $(document).on('click','.sp1',function(){
    if(!$(this).text()) return;

    updateCount(this,-1);

  })

  function updateCount(self,tag){
    var parent = $(self).parents('tr');
    var id = parent.attr('data-id');
    var count = parent.find('.sp2').val() * 1;

    count += tag;

    if(count <= 1){
      parent.find('.sp1').text('');
    }
    parent.find('.sp2').val(count);

    var price = parent.find('.td3 p').text();
    parent.find('.td5 p').text((price * count).toFixed(2))

    clearTimeout(timer);
    timer = setTimeout(() => {
        APICartUpdate({
        id,
        count
      }).then(({code}) => {
        if(code){
          
        }
      })
    },500)
    getTotal()
  }

  // 全选
  $('.check-all').change(function () {
    $('.check-one').prop('checked', $(this).prop('checked'))
    getTotal()
  })

  // 单选
  $(document).on('click', '.check-one', function () {
    checkAll();
  })

  function checkAll() {
    if ($('.check-one').length === $('.check-one:checked').length) {
      $('.check-all').prop('checked', true)
    } else {
      $('.check-all').prop('checked', false)
    }
    getTotal()
  }

  // 删除
  $(document).on('click', '.layui-icon-delete', function () {
    APICartDelete({
      ids: JSON.stringify([$(this).parents('tr').attr('data-id')])
    }).then(({ code, msg }) => {
      if (code) {
        $(this).parents('tr').remove();
        checkAll();
        layer.msg('删除成功')
      } else {
        layer.msg(msg)
      }
    })
  })
})

function getTotal() {
  var count = 0;
  var total = 0;
  var variety = 0;
  $.each($('.check-one:checked'), function (_, item) {
    variety += $(this).parents('tr').find('.sp2').val() / $(this).parents('tr').find('.sp2').val()
    count += $(this).parents('tr').find('.sp2').val() * 1
    total += $(this).parents('tr').find('.td5 p').text() * 1
  });

  $('#center-footer .td2 .sp1').text(variety);
  $('#center-footer .td2 .sp2').text(count);
  $('#center-footer .td3 .p2').text(total);
}
